package com.szx.kaihei.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szx.kaihei.Enums.CaptchaType;
import com.szx.kaihei.exceptions.CustomException;
import com.szx.kaihei.exceptions.ExceptionEnums;
import com.szx.kaihei.pojo.User;
import com.szx.kaihei.pojo.dto.LoginDto;
import com.szx.kaihei.pojo.vo.UserInfoVo;
import com.szx.kaihei.service.CodeService;
import com.szx.kaihei.service.SmsService;
import com.szx.kaihei.service.UserService;
import com.szx.kaihei.mapper.UserMapper;
import com.szx.kaihei.util.JwtUtil;
import com.szx.kaihei.util.UserLocalStorageUtil;
import com.szx.kaihei.util.PwdToSecretUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
* @author Szx
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-06-10 08:25:36
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private CodeService codeService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SmsService  smsService;

    /**
     * 用户登录
     * @param loginDto
     * @return
     */
    @Override
    public String userLogin(LoginDto loginDto) {
        User entity = lambdaQuery().eq(User::getPhone, loginDto.getPhone()).one();
        return loginVerify(loginDto, entity);
    }

    @Override
    public String userRegister( LoginDto loginDto) {
        if (loginDto == null || StrUtil.isEmpty(loginDto.getPhone()) || StrUtil.isEmpty(loginDto.getCode())){
            throw new CustomException(ExceptionEnums.PARAM_ERROR);
        }
        boolean verifyCode = codeService.verifyCode(loginDto.getPhone(), loginDto.getCode(), CaptchaType.REGISTER);
        if (!verifyCode){
            throw new CustomException(ExceptionEnums.USER_CODE_ERROR);
        }
        User user = User.builder()
                .phone(loginDto.getPhone())
                .nickname("用户" + RandomUtil.randomString(16))
                .status(1).build();
        try {
            save(user);
        } catch (Exception e) {
            throw new CustomException(ExceptionEnums.USER_EXIST );
        }


        return JwtUtil.generateToken(user.getId(), user.getNickname());
    }

    /**
     * 获取用户信息
     * @param id
     * @return
     */
    @Override
    public UserInfoVo getUserById(Long id) {

        User userInfo = getById(id);
        if (userInfo == null){
            throw new CustomException(ExceptionEnums.USER_NOT_EXIST);
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);

        return userInfoVo;
    }

    /**
     * 根据Token获取当前用户信息
     * @return
     */
    @Override
    public UserInfoVo getUserByToken() {
        User user = UserLocalStorageUtil.get();
        if (user == null){
            throw new CustomException(ExceptionEnums.PARAM_ERROR);
        }

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(user, userInfoVo);
        return userInfoVo;
    }

    /**
     * 登录验证逻辑
     * @param loginDto
     * @param user
     * @return
     */
    public String loginVerify(LoginDto loginDto,User user){

        if (user == null){
            throw new CustomException(ExceptionEnums.USER_NOT_EXIST);
        }
        if(loginDto.getPassword() != null) {
            //效验图像验证码
            boolean verifyCodeByImage = codeService.verifyCodeByImage(loginDto.getPhone(), loginDto.getImageCaptcha(), CaptchaType.LOGIN_IMAGE);
            if (!verifyCodeByImage){
                throw new CustomException(ExceptionEnums.USER_CODE_ERROR);
            }

            //密码登录
            boolean verify = PwdToSecretUtil.verify(loginDto.getPassword(), user.getPassword());
            if (verify){
                return JwtUtil.generateToken(user.getId(), user.getNickname());
            }else{
                throw new CustomException(ExceptionEnums.USER_PASSWORD_ERROR);
            }

        }else if(loginDto.getCode() !=  null){
            //验证码登录
            boolean verifyCode = codeService.verifyCode(loginDto.getPhone(), loginDto.getCode(), CaptchaType.LOGIN_PHONE);
            if (!verifyCode){
                throw new CustomException(ExceptionEnums.USER_CODE_ERROR);
            }
            return JwtUtil.generateToken(user.getId(), user.getNickname());
        }else {
            throw new CustomException(ExceptionEnums.PARAM_ERROR);
        }
    }
}




